package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.R;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpServletRequest request){
        //获取用户输入的数据
        String username = employee.getUsername();
        String password = employee.getPassword();

        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //查询数据库
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        //sql语句  select * from   where username = ?;
        wrapper.eq(Employee::getUsername,username);   //username = ?
        Employee one = employeeService.getOne(wrapper); //select * from

        if (one == null){
            return R.error("用户名或密码错误");
        }
        if (!one.getPassword().equals(password)){
            return R.error("用户名或密码错误");
        }
        if (one.getStatus() == 0){
            return R.error("该用户已禁用");
        }

        //将数据放到session中
        request.getSession().setAttribute("employee",one.getId());
        return R.success(one);
    }

    @PostMapping("/logout")
    public R<String> loginOut(HttpServletRequest request){
        //将session中的数据清除
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

}
